package com.ruoyi.framework.utils;

import com.ruoyi.common.utils.bean.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;

import java.util.List;

/**
 * bean copy 工具类
 */
public class BeanCopyUtils {
    /**
     * 对象复制
     * @param source 源对象
     * @param clazz 目标对象class
     * @param <T>
     * @return
     */
    public static <T> T copyProperties(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }

        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        BeanUtils.copyProperties(source, obj);
        return obj;
    }

    /**
     * 列表复制
     * @param source 源列表
     * @param clazz 目标列表class
     * @param <T>
     * @return
     */
    public static <T> List<T> copyListProperties(List source, Class<T> clazz) {
        List<T> target = Lists.newArrayList();

        if (CollectionUtils.isEmpty(source)) {
            return target;
        }

        for(Object obj : source){
            T o = copyProperties(obj,clazz);
            target.add(o);
        }

        return target;
    }
}
